package _21Lock锁机制;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Ticket implements Runnable{
    private int total=100;
    //获取锁对象
    Lock lock =new ReentrantLock();
    @Override
    public void run() {

        String name = Thread.currentThread().getName();
        while (true){
            try {
                //加锁
                lock.lock();
                System.out.println(name+"抢到锁了，开始购票");
                if (total > 0) {
                    total = total - 1;
                    System.out.println(name + "购票成功，剩余票数为：" + total);

                }else {

                    System.out.println("没票了，下次再来");
                    break;
                }
            }finally {
                //解锁
                lock.unlock();
            }


        }








//        有问题的写法:锁可能不会被释放
//        while (true){
//            //加锁
//            lock.lock();
//            System.out.println(name+"抢到锁了，开始购票");
//            if (total > 0) {
//                total = total - 1;
//                System.out.println(name + "购票成功，剩余票数为：" + total);
//
//            }else {
//
//                System.out.println("没票了，下次再来");
//                break;
//            }
//            //解锁
//            lock.unlock();
//        }

    }

}
